package com.fj.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fj.entity.User;
import com.fj.response.Result;
import com.fj.response.ResultCode;
import com.fj.service.UserService;
import com.fj.shiro.JWTUtil;
import com.fj.vo.TokenVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author mo
 * @Description: 登录控制器
 * @date 2020-09-01 15:58
 */
@Api(value = "登录控制器")
@RestController
@RequestMapping(value = "/api")
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @ApiOperation(value = "登录")
    @PostMapping(value = "/dologin", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result login(@ApiParam(name = "name", value = "登录用户名") @RequestParam("name") String userCode,
                        @ApiParam(name = "password", value = "登录密码") @RequestParam("password") String userPassword,
                        HttpServletRequest request) {
        if (StrUtil.isEmpty(userCode) || StrUtil.isEmpty(userPassword)) {
            //当用户编码或用户密码为空的时候
            return Result.error(ResultCode.PARAM_IS_BLANK);
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserCode,userCode);
        User user = userService.getOne(wrapper);
        if (user == null) {
            return Result.error(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }
        if (SecureUtil.md5(userPassword).equals(user.getUserPassword())) {
            //当密码不匹配时返回错误信息
            return Result.error(ResultCode.USER_CREDENTIALS_ERROR);
        }
        String jwtToken = null;
        try {
            jwtToken = JWTUtil.sign(userCode, SecureUtil.md5(userPassword));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        TokenVo tokenVo = new TokenVo(jwtToken, System.currentTimeMillis() + 2 * 3600 * 1000, System.currentTimeMillis());
        //将用户信息存储到redis中，以jwtToken做为key，跟需求有一些出入，不区分移动端和PC端
        //stringRedisTemplate.opsForValue().set(jwtToken, JSONUtil.toJsonStr(user), 2, TimeUnit.HOURS);
        return Result.ok().data("token",tokenVo);
    }

    @ApiOperation(value = "用户退出")
    @GetMapping(value = "/logout", produces = MediaType.APPLICATION_JSON_VALUE)
    public Result logout(HttpServletRequest request) {
        //从request中取出cookie 里面的 token
        String token = "";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if ("token".equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }
        //清除redis中的信息
        stringRedisTemplate.delete(token);
        return Result.ok();
    }

    @RequestMapping(value = "/wx/login/callback")
    public String wxLoginCallBack() {
        log.info("进入微信登录回调");
        return null;
    }
}
